package util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class FeatureMap {

    private Map<String, Long> map;

    private String delim;

    private FeatureMap(Map<String, Long> map, String delim) {
        this.map = map;
        this.delim = delim;
    }

    public static FeatureMap parse(String line, String delim) {
        FeatureMap ret = FeatureMap.createNewFeatureMap(delim);
        String[] features = line.split("\t");
        for (String feature : features) {
            String[] t = feature.split(delim);
            String k = t[0];
            if (t.length > 1) {
                Long v = Long.parseLong(t[1]);
                ret.addFeature(k, v);
            } else {
                ret.addFeature(k, 1L);
            }
        }
        return ret;
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (String k : map.keySet()) {
            sb.append(k);
            long v = map.get(k);
            if (v != 1) {
                sb.append(delim);
                sb.append(v);
            }
            sb.append("\t");
        }
        return sb.toString().trim();
    }

    public void add(FeatureMap... maps) {
        for (FeatureMap a : maps) {
            for (String k : a.map.keySet()) {
                this.addFeature(k, a.map.get(k));
            }
        }
    }

    public static FeatureMap createNewFeatureMap(String delim) {
        return new FeatureMap(new HashMap<String, Long>(), delim);
    }

    public void addFeature(String key, Long value) {
        if (!key.isEmpty()) {
            if (map.containsKey(key)) {
                map.put(key, map.get(key) + value);
            } else {
                map.put(key, value);
            }
        }
    }

    public Set<String> featureSet() {
        return map.keySet();
    }

    public long get(String key) {
        return map.get(key);
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }

    public int size() {
        return map.size();
    }
    
}
